package com.caiyi.tips.user.controller;

import com.caiyi.tips.core.VO.ResultVO;
import com.caiyi.tips.core.enums.ResultEnum;
import com.caiyi.tips.core.servlet.yzm.VerificationCodeTool;
import com.caiyi.tips.core.util.CheckUtil;
import com.caiyi.tips.core.util.StringUtil;
import com.caiyi.tips.core.util.TipsUtil;
import com.caiyi.tips.user.DTO.SmsDTO;
import com.caiyi.tips.user.DTO.UserRegisterDTO;
import com.caiyi.tips.user.bean.SmsBean;
import com.caiyi.tips.user.bean.UserBean;
import com.caiyi.tips.user.exception.UserException;
import com.caiyi.tips.user.service.PublicService;
import com.caiyi.tips.user.service.SmsService;
import com.caiyi.tips.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/*
 * @author Cliff.ZhouYang
 * @date 2017/11/8 15:42
 */

@RequestMapping
@RestController
@Slf4j
@Validated
@Api(value = "平台通用接口", tags = "2.通用接口", description = "平台通用接口", protocols = "http")
public class PublicController {
    @Autowired
    private PublicService publicService;

    @Autowired
    private SmsService smsService;

    @GetMapping(value = "/checkPhone")
    @ApiOperation(value = "注册时手机号检测", notes = "检测手机号是否有重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name="phone", value = "手机号码", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name="type", value = "用户类型", required = true, dataType = "Integer", paramType = "body"),
            @ApiImplicitParam(name="checkType", value = "手机检测类型，0 注册，1找回密码", required = true, dataType = "Integer", paramType = "body")
    })
    public ResultVO checkPhone(String phone, Integer type, Integer checkType) {// type 0专家 1普通用户
        if (type == null) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不能为空");
        }
        if (type != 1 && type != 0) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不正确");
        }
        if (StringUtils.isEmpty(phone)) {
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(),"请输入手机号");
        }
        if(phone.length() != 11){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(),"手机号不得少于11位，请重新输入");
        }
        if (!CheckUtil.isMobilephone(phone)) {
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "无效手机号，请重新输入");
        }
        boolean flag = publicService.isExistPhone(phone, type );
        if(checkType ==0 && flag){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "已注册手机号，请重新输入");
        }
        if(checkType ==1 && !flag){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "未注册手机号，请重新输入");
        }
        return ResultVO.okMsg("手机号合法");
    }

    @GetMapping(value = "/checkNickId")
    @ApiOperation(value = "用户名检测", notes = "检测用户名是否有重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name="nickid", value = "用户名", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name="type", value = "用户类型", required = true, dataType = "Integer", paramType = "body")
    })
    public ResultVO checkNickId(String nickid, Integer type) {//0专家 1普通用户
        if (type == null) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不能为空");
        }
        if (type != 1 && type != 0) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不正确");
        }
        if (StringUtils.isEmpty(nickid)) {
            throw new UserException(ResultEnum.USER_NICKID_ERROR.getCode(),"用户名不能为空");
        }
        if (nickid.length()>14 || nickid.length()<2) {
            throw new UserException(ResultEnum.USER_NICKID_ERROR.getCode(),"用户名格式不正确");
        }
        if (CheckUtil.checkIsNumber(nickid)) {
            throw new UserException(ResultEnum.USER_NICKID_ERROR.getCode(),"用户名格式不能为纯数字");
        }
        if (!CheckUtil.checkUserName(nickid)) {
            throw new UserException(ResultEnum.USER_NICKID_ERROR.getCode(),"用户名格式不正确");
        }
     /*   if(){
            throw new UserException(ResultEnum.USER_NICKID_RESEVER_ERROR.getCode(),"该用户名为预留用户名，请扫码联系运营人员");
        }
        if(){
            throw new UserException(ResultEnum.USER_NICKID_ILLEGAL_ERROR.getCode(),"包含非法词汇，请重新输入");
        }*/
        return  publicService.checkNickid(nickid,type);
    }





    @ApiOperation(value = "密码找回，验证 手机号 图形验证码 短信验证码 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name="nickid", value = "用户名", required = true, dataType = "String", paramType = "body"),
            @ApiImplicitParam(name="type", value = "用户类型", required = true, dataType = "Integer", paramType = "body")
    })
    @PostMapping(value = "/findPwdOneStep")
    public ResultVO findPwdOneStep(HttpServletRequest request, SmsDTO dto){
        if (dto.getUserType() != 1 && dto.getUserType() != 0) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不正确");
        }
        if (StringUtil.isEmpty(dto.getImgYzm())) {
            throw new UserException(ResultEnum.USER_TYPE_ERROR.getCode(),"用户类型不能为空");
        }
        HttpSession localHttpSession = request.getSession(true);
        String checkRand = String.valueOf(localHttpSession.getAttribute("rand"));
        if (StringUtils.isEmpty(dto.getPhone())) {
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(),"请输入手机号");
        }
        if(dto.getPhone().length() != 11){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(),"手机号不得少于11位，请重新输入");
        }
        if (!CheckUtil.isMobilephone(dto.getPhone())) {
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "无效手机号，请重新输入");
        }
        int count =Integer.valueOf(localHttpSession.getAttribute("randErrCount").toString()) ;
        count++;
        localHttpSession.setAttribute("randErrCount", count);
        if(!dto.getImgYzm().equalsIgnoreCase(checkRand)){
            throw new UserException(ResultEnum.USER_RAND_ERROR.getCode(),"图形验证码不正确，请重新输入");
        }
        if(count>3){
            throw new UserException(ResultEnum.USER_RAND_INVALID_ERROR.getCode(),"图形验证码失效，请重新输入");
        }
        boolean flag = publicService.isExistPhone(dto.getPhone(), dto.getUserType() );
        if(dto.getYzmType() ==0 && flag){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "已注册手机号，请重新输入");
        }
        if(dto.getYzmType()  ==1 && !flag){
            throw new UserException(ResultEnum.USER_PHONE_ERROR.getCode(), "未注册手机号，请重新输入");
        }
        //检测短信验证码
        SmsBean smsBean = new SmsBean();
        BeanUtils.copyProperties(dto, smsBean);
        smsService.checkSendMsg(smsBean);
        return ResultVO.okMsg("密码找回验证通过");
    }


    @ApiOperation(value = "密码找回，确认密码")
    @PostMapping(value = "/findPwdTwoStep")
    public ResultVO findPwdTwoStep(UserBean userBean){
        String  password = userBean.getPassword();
        if (!StringUtils.isEmpty(password)) {
            password = DigestUtils.md5Hex(password);
            userBean.setPassword(password);
        }
        publicService.updateUserInfo(userBean);
        return ResultVO.okMsg("密码修改成功");
    }

    @GetMapping("/yzm")
    @ApiOperation(value = "获取图形验证码")
    public String createImgYzm(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
        HttpSession localHttpSession = request.getSession(true);
        VerificationCodeTool vct = new VerificationCodeTool();
        BufferedImage image = vct.drawVerificationCodeImage();
        ServletOutputStream localServletOutputStream = response.getOutputStream();
        localHttpSession.setAttribute("rand", vct.getXyresult() + "");
        localHttpSession.setAttribute("randErrCount", 0);
        try {
            ImageIO.write(image, "JPEG", localServletOutputStream);
            log.info("验证码生成成功,内容:" + vct.getRandomString() + " 结果:" + vct.getXyresult());
        } catch (IOException e) {
            throw new Exception();
        } finally {
            localServletOutputStream.flush();
            localServletOutputStream.close();
        }
        return null;
    }
}
